<?php

namespace App;

use App\Jobs\CreateDefaultAvatarJobs;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
use Overtrue\LaravelFollow\Traits\CanFavorite;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanLike;
use Overtrue\LaravelFollow\Traits\CanSubscribe;
use Overtrue\LaravelFollow\Traits\CanVote;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable, CanFavorite, CanLike, CanFollow, CanVote,
        CanSubscribe, CanBeFollowed, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'cache',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    const CACHE_FIELDS = [
        'threads_count' => 0,
        'comments_count' => 0,
        'likes_count' => 0,
        'followings_count' => 0,
        'followers_count' => 0,
        'subscriptions_count' => 0,
    ];

    public function getAvatarAttribute()
    {
        if (empty($this->attributes['avatar'])) {
            dispatch(new CreateDefaultAvatarJobs($this));
        }

        return $this->attributes['avatar'];
    }

    public function articles()
    {
        return $this->hasMany(Article::class, 'founder_id');
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function refreshCache()
    {
        $this->update(['cache' => \array_merge(self::CACHE_FIELDS, [
            'articles_count' => $this->articles()->count(),
            'comments_count' => $this->comments()->count(),
            'likes_count' => $this->likes()->count(),
            'followings_count' => $this->followings()->count(),
            'followers_count' => $this->followers()->count(),
            'subscriptions_count' => $this->subscriptions()->count(),
        ])]);
    }
}
